<template>
  <div class="result">
    <el-card class="card">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>成绩管理</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="text">
          <div>
            <el-select v-model="state" placeholder="请选择课程"  style="width:300px" @change="handleChange1">
              <el-option v-for="item of list" :key="item.cid" :label="item.name" :value="item.cid"></el-option>
            </el-select>
            <el-select v-model="teacher" placeholder="请选择教师"  style="width:250px" @change="handleChange2">
                <el-option v-for="item of teacherlist" :key="item.tid" :label="item.name" :value="item.tid"></el-option>
            </el-select>
            <el-button type="primary" @click="download()">下载填写模板</el-button>
          </div>
          <div class="upload-demo">
            <el-select v-model="cid" placeholder="请选择课程"  style="width:300px" @change="handleChange1">
              <el-option v-for="item of list" :key="item.cid" :label="item.name" :value="item.cid"></el-option>
            </el-select>
            <el-select v-model="tid" placeholder="请选择教师"  style="width:250px" @change="handleChange2">
                <el-option v-for="item of teacherlist" :key="item.tid" :label="item.name" :value="item.tid"></el-option>
            </el-select>
             <el-upload
            ref="upload"
            accept=".xlsx,.xls"
            :action="actionURL()"
            :headers="headers"
            :data="uploadData"
            :before-upload="beforeup"
            :on-success="backinfo"
            :on-error="errorinfo"
            :file-list="fileList"
            :auto-upload="false"
            :on-exceed="tomuchfile"
            :limit="1"
            style="display:inline"
          >
            <el-button slot="trigger" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx、xls文件，文件名必须为：课程+教师，格式为：文件名.xlsx或文件名.xls</div>
          </el-upload>
          </div>
        </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'result',
  data () {
    return {
      uploadData: {
        timetable: this.timeid,
        file: this.fileList
      },
      state: '',
      timeid: '',
      tid: '',
      cid: '',
      list: [],
      timelist: [],
      fileList: [],
      teacher: '',
      teacherlist: [],
      teacherName: '',
      courseName: ''
    }
  },
  components: {},
  created () {
    this.getassessmentlist()
    this.getteacherlist()
    this.gettimelist()
  },
  computed: {
    headers () {
      return {
        'token': sessionStorage.getItem('token')
      }
    }
  },
  methods: {
    // 获取课程信息
    async getassessmentlist () {
      // 需要授权的API必须设置请求头
      const AUTH_TOKEN = sessionStorage.getItem('token')
      this.$http.defaults.headers.common['token'] = AUTH_TOKEN
      // 后台token的key是token
      this.$http.defaults.headers.get['Content-Type'] = 'application/json'
      this.$http.defaults.headers.get['Accept'] = 'application/json'
      const res = await this.$http.get(`course/list?pageNum=1&pageSize=9999&name=`)
      // console.log(res)
      const {code, msg, page} = res.data
      // console.log(this.status)
      if (code === 200) {
        this.list = page.list
      } else {
        console.log(msg)
      }
    },
    // 获取教师信息
    async getteacherlist () {
      const res = await this.$http.get(`teacher/list?pageNum=1&pageSize=9999&name=`)
      // console.log(res)
      const {code, msg, page} = res.data
      // console.log(this.status)
      if (code === 200) {
        this.teacherlist = page.list
      } else {
        console.log(msg)
      }
    },
    // 获取课程安排管理
    async gettimelist () {
      const res = await this.$http.get(`time_table/list?pageNum=1&pageSize=9999&name=`)
      // console.log(res)
      const {code, msg, page: {list}} = res.data
      // console.log(this.status)
      if (code === 200) {
        this.timelist = list
      } else {
        console.log(msg)
      }
    },
    // 下载文件
    download () {
      const AUTH_TOKEN = sessionStorage.getItem('token')
      this.$http.defaults.headers.common['token'] = AUTH_TOKEN
      this.$http.get(`score/excel?courseId=${this.state}&teacherId=${this.teacher}`, {responseType: 'arraybuffer'}).then((res) => {
        console.log(res)
        if (res.status === 200) {
          if (res.data.code === 500) {
            this.$message.error(res.msg)
          }
          var filename = this.courseName + '-' + this.teacherName
          let url = window.URL.createObjectURL(new Blob([res.data], {type: 'application/vnd.ms-excel;charset=UTF-8'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', filename)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
          this.$message.success('下载成功！')
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {
        this.$message.error('请检查数据的完整性！')
      })
    },
    // 获取select里的label值
    handleChange1 (val) {
      // 传进来的val是select组件选中的value值
      var obj = {}
      obj = this.list.find(function (item) {
        return item.cid === val
      })
      this.courseName = obj.name
    },
    handleChange2 (val) {
      // 传进来的val是select组件选中的value值
      var obj = {}
      obj = this.teacherlist.find(function (item) {
        return item.tid === val
      })
      this.teacherName = obj.name
    },
    // 上传成功回调事件
    backinfo (response, file, fileList) {
      console.log(file)
      this.fileList = []
      // console.log(response)
      if (response.code === 200) {
        this.$message.success('上传成功！')
        // 课程总体达成度
        this.$http.get(`reach/total_reach/${this.cid}`).then((res) => {
          if (res.data.status === 200) {
            // console.log(1)
            // 成功之后发课程个体达成度请求
            this.$http.get(`reach/single_reach/${this.cid}`).then((mes) => {
            })
          }
        })
      } else {
        this.$message.error(response.msg)
      }
      // console.log(1, this.actionURL)
      // console.log(2, this.timeid)
    },
    // 上传失败回调事件
    errorinfo (response, file, fileList) {
      this.$message.error('上传失败，请重试！')
    },
    // 上传之前的验证
    beforeup (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!extension && !extension2) {
        this.$message.error('上传模板只能是 xls、xlsx格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传模板大小不能超过 10MB!')
      }
    },
    // 上传的文件超出个数
    tomuchfile () {
      this.$message.error('只能上传单个文件！')
    },
    // 上传地址
    actionURL () {
      // return `http://39.98.227.154:8081/auth/sys/score/excel?courseId=${this.cid}&teacherId=${this.tid}`
      return `http://119.23.174.22:8080/auth/sys/score/excel?courseId=${this.cid}&teacherId=${this.tid}`
    },
    // 上传文件
    async submitUpload () {
      let _this = this
      setTimeout(function () {
        _this.$refs.upload.submit()
      }, 200)
    }
  }
}
</script>

<style scoped lang="stylus">
.result,.card
  height 100%
  min-width: 1200px
  .text
    padding-top 15px
    .upload-demo
      padding-top 20px
</style>
